package com.loubobooo.personal.blog.controller.backend;

import com.loubobooo.personal.blog.entity.Page;
import com.loubobooo.personal.blog.entity.vo.*;
import com.loubobooo.personal.blog.service.PageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import java.util.Date;
import java.util.List;

@Controller @RequestMapping("/admin/page") public class PageManageController {

    @Autowired private PageService pageService;

    //后台页面列表显示
    @RequestMapping(value = "") public ModelAndView index() {
        ModelAndView modelAndView = new ModelAndView();
        List<PageVO> pageVOList = pageService.listPage(null);
        modelAndView.addObject("pageVOList", pageVOList);
        modelAndView.setViewName("Admin/Page/index");
        return modelAndView;
    }

    //后台添加页面页面显示
    @RequestMapping(value = "/insert") public ModelAndView insertPageView() {
        ModelAndView modelAndView = new ModelAndView();

        modelAndView.setViewName("Admin/Page/insert");
        return modelAndView;
    }

    //后台添加页面提交操作
    @RequestMapping(value = "/insertSubmit", method = RequestMethod.POST) public String insertPageSubmit(Page page) {

        //判断别名是否存在
        PageVO checkPage = pageService.getPageByKey(null, page.getPageKey());
        if (checkPage == null) {
            Date date = new Date();
            page.setPageCreateTime(date);
            page.setPageUpdateTime(date);
            page.setPageStatus(1);
            pageService.insertPage(page);
        }
        return "redirect:/admin/page";
    }

    //删除页面
    @RequestMapping(value = "/delete/{id}") public String deletePage(@PathVariable("id") Integer id) {
        //调用service批量删除
        pageService.deletePage(id);
        return "redirect:/admin/page";
    }

    //编辑页面页面显示
    @RequestMapping(value = "/edit/{id}") public ModelAndView editPageView(@PathVariable("id") Integer id) {
        ModelAndView modelAndView = new ModelAndView();

        PageVO pageVO = pageService.getPageById(id);
        modelAndView.addObject("pageVO", pageVO);

        modelAndView.setViewName("Admin/Page/edit");
        return modelAndView;
    }

    //编辑页面提交
    @RequestMapping(value = "/editSubmit", method = RequestMethod.POST) public String editPageSubmit(Page page) {
        PageVO checkPage = pageService.getPageByKey(null, page.getPageKey());
        //判断别名是否存在且不是这篇文章
        if (checkPage.getPageId() == page.getPageId()) {
            page.setPageUpdateTime(new Date());
            pageService.updatePage(page);
        }
        return "redirect:/admin/page";
    }

}



